﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Base;
using Core.Base;
using Components;
using Core;
using ERP.BusinessEntities.Base;
using ERP.BusinessEntities.Factory;
using PopupControl;
using Core.Component;

namespace Components
{
    public delegate void IDValidatedHandler(Object sender, EventArgs e);

    
    public partial class SGVLookUp : SGVTextBoxLookUp 
    {
        #region Fields

        // a Panel for displaying
        private LookUpPanel panelPopup;

        #endregion Fields

        #region Properties

        // the parent Form of this control
        
        // minimum characters to be typed before suggestions are displayed
         

        #endregion
        
        public SGVLookUp()
            :base()
        {
            LookUpStl = LookUpStyle.Dropdown;
            
            BindingPropertyName = "ID";
            
            InitializeComponent();

            this.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.MinTypedCharacters = 1;

            #region Panel Popup
            panelPopup = new LookUpPanel();
            this.panelPopup.Visible = false;
            this.panelPopup.Font = this.Font;
            this.panelPopup.ClientSize = new System.Drawing.Size(1, 1);
            this.panelPopup.Name = "SuggestionPanel";
            this.panelPopup.Padding = new System.Windows.Forms.Padding(0, 0, 0, 0);
            this.panelPopup.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
            this.panelPopup.Text = "";
            this.panelPopup.PerformLayout();
            panelPopup.dataGridView1.KeyDown += new KeyEventHandler(PanelPopup_KeyDown);
            panelPopup.dataGridView1.MouseDoubleClick += new MouseEventHandler(panelPopup_MouseDoubleClick);
            #endregion

            // the events to be fired if an item is selected
        }

        #region Event

        #region Event

        public override void Control_KeyDown(object sender, KeyEventArgs e)
        {
            //base.this_KeyDown(sender, e);
            if ((e.KeyCode == Keys.Escape))
            {
                if (isPopupShow == true)
                    HideSuggestionListBox();
                else
                    this.ID = 0;
                // work is done
                e.Handled = true;
            }
            // if user presses key.up
            else if ((e.KeyCode == Keys.Up))
            {
                // move the selection in listbox one up
                panelPopup.MoveSelectionInListBox((panelPopup.SelectedIndex - 1));
                // work is done
                e.Handled = true;
            }
            // on key.down
            else if ((e.KeyCode == Keys.Down))
            {
                if (isPopupShow == false && AllowLookUp)
                    LookUp_Click(null, new EventArgs());
                //move one down
                panelPopup.MoveSelectionInListBox((panelPopup.SelectedIndex + 1));
                e.Handled = true;
            }
            else if ((e.KeyCode == Keys.PageUp))
            {
                //move 10 up
                panelPopup.MoveSelectionInListBox((panelPopup.SelectedIndex - 10));
                e.Handled = true;
            }
            else if ((e.KeyCode == Keys.PageDown))
            {
                //move 10 down
                panelPopup.MoveSelectionInListBox((panelPopup.SelectedIndex + 10));
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Enter)
            {
                if (AllowLookUp && panelPopup.dataGridView1.Rows.Count > 0 && panelPopup.SelectedIndex > -1)
                    SelectItemOnList();
                else
                    // select the item in the ListBox
                    SelectItemText();
                e.Handled = true;
            }
            else
                base.Control_KeyDown(sender, e);
        }
        public override void this_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (isTextChanged == false) return;
                //  HideSuggestionListBox();
                if (this.DesignMode == true) return;

                String strText = this.Text;

                if (String.IsNullOrEmpty(strText) == true || strText.Trim().Length < MinTypedCharacters)
                {
                    HideSuggestionListBox();
                    ID = 0;
                    return;
                }

                if (AllowLookUp)
                {
                    ShowSuggetionBox();
                    RefreshDropdownLit(strText.Trim());
                }

            }
            catch (Exception ex)
            {

            }

        }

        public override void Control_LostFocus(object sender, EventArgs e)
        {
            base.Control_LostFocus(sender, e);

            if (panelPopup.Focused == false)
                HideSuggestionListBox();
        }

        #endregion

        //private void MoveSelectionInListBox(int Index)
        //{
        //    // beginning of list
        //    if (Index <= -1)
        //    { this.SelectedIndex = 0; }
        //    else
        //        // end of liste
        //        if (Index > (listBox.Items.Count - 1))
        //        {
        //            SelectedIndex = (listBox.Items.Count - 1);
        //        }
        //        else
        //        // somewhere in the middle
        //        { SelectedIndex = Index; }
        //}

        // event for any key pressed in the ListBox
        private void PanelPopup_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // on enter
            if (e.KeyCode == Keys.Enter)
            {
                // select the current item
                SelectItemOnList();
                // work done
                e.Handled = true;
            }
        }

        // event for MouseClick in the ListBox
        private void PanelPopup_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // select the current item
            SelectItemOnList();
        }

        // event for DoubleClick in the ListBox
        private void panelPopup_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // select the current item
            SelectItemOnList();
        } 
        #endregion

        // selects the current item
        public bool SelectItemOnList()
        {
            try
            {
                // if the ListBox is not empty
                if (((panelPopup.dataGridView1.Rows.Count > 0) && (panelPopup.SelectedIndex > -1)) && panelPopup.dataGridView1.SelectedCells.Count > 0)
                {
                    // set the Text of the TextBox to the selected item of the ListBox
                    //this.Text = this.listBox.SelectedItem.ToString();
                    isTextChanged = false;
                    //this.Text = this.listBox.SelectedValue.ToString();
                    this.ID = Convert.ToInt32(panelPopup.dataGridView1[AppContext.cstID, panelPopup.SelectedIndex].Value);
                    isTextChanged = true;
                    // and hide the ListBox
                    this.HideSuggestionListBox();
                }
                else
                {
                    this.ID = 0;
                    this.HideSuggestionListBox();
                }
            }
            catch (Exception ex)
            {
            }

            return true;
        }

        public override void SelectItemText()
        {
            if (String.IsNullOrEmpty(this.Text) || this.Text.Trim().Length == 0)
            {
                ID = 0;
            }
            else
            {
                DataTable dt = GetSearchDataSet(this.Text.Trim());
                if (dt == null || dt.Rows.Count == 0)
                {
                    ID = 0;
                }
                else if (dt.Rows.Count == 1)
                {
                    ID = Convert.ToInt32(dt.Rows[0][AppContext.cstID]);
                    HideSuggestionListBox();
                }
                else
                {
                }
            }
        }

        public override void RefreshDropdownLit(String text)
        {
            try
            {
                if (isTextChanged == false) return;
                if (this.DesignMode == true) return;

                DataTable dt = GetSearchDataSet(text);
                panelPopup.SetDataSource(dt);
                
                //if(isPopupShow == false)
                //    ShowSuggetionBox();
            }
            catch (Exception ex)
            {
            }
            
        }
        
        public override void ShowSuggetionBox()
        {
            if (AllowLookUp == false) return;
            // if there is a ParentForm
            if ((ParentScreen != null) && isPopupShow == false)
            {
                panelPopup.Hide();
                isPopupShow = true;
                // get its width
                panelPopup.Width = this.Width;
                // calculate the remeining height beneath the TextBox
               // panelPopup.Height = this.ParentForm.ClientSize.Height - this.Height - this.Location.Y;

                Point pOnScreen = this.PointToScreen(this.Location);
                Point pFormOnScreen = this.FindForm().PointToScreen(this.Location);

                Point p = new Point(pOnScreen.X - pFormOnScreen.X, this.Height + pOnScreen.Y - pFormOnScreen.Y +2);

                // and the Location to use
                panelPopup.Location = p;
                // Panel and ListBox have to be added to ParentForm.Controls before calling BingingContext
                if (!this.ParentScreen.Controls.Contains(panelPopup))
                {
                    // add the Panel and ListBox to the PartenForm
                    this.ParentScreen.Controls.Add(panelPopup);
                }

                panelPopup.Show();

                //Form frm = this.FindForm();
                //if (frm is SGVScreen)
                //{
                //    ((SGVScreen)frm).animator.AnimationType = AnimatorNS.AnimationType.VertSlide;
                //    ((SGVScreen)frm).animator.Show(panelPopup);
                //}
                panelPopup.BringToFront();

                // Update the listBox manually - List<string> dosn't support change events
                // this is the DataSource approche, this is a bit tricky and may cause conflicts,
                // so in case fall back to AddRange approache (see Excursus)
                //((CurrencyManager)listBox.BindingContext[CurrentAutoCompleteList]).Refresh();
            }
        }

        public override void HideSuggestionListBox()
        {
            if ((ParentScreen != null))
            {
                // hiding the panel also hides the listbox
                //panelPopup.Hide();
                Form frm = this.FindForm();
                if (frm is SGVScreen)
                {
                    ((SGVScreen)frm).animator.AnimationType = AnimatorNS.AnimationType.VertSlide;
                    ((SGVScreen)frm).animator.Hide(panelPopup);
                }
                isPopupShow = false;
                panelPopup.dataGridView1.DataSource = null;
                // now remove it from the ParentForm (Form1 in this example)
                if (this.ParentScreen.Controls.Contains(panelPopup))
                {
                    this.ParentScreen.Controls.Remove(panelPopup);
                }
            }
        }

        public override void Init()
        {
            base.Init();

            
            
            panelPopup.InitView(this);

            //if (AllowDrill == false)
            //    panelRight.Size = new Size(0, 0);

            //panelLeft.Size = new Size(0, 0);
        }

        

        public override void LookUp_Click(object sender, EventArgs e)
        {
            if (isPopupShow == false)
            {
                ShowSuggetionBox();
                RefreshDropdownLit(this.Text.Trim());
            }
            else
                HideSuggestionListBox();
        }
    }
}
